package org.itboys.admin.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.itboys.admin.dto.AdminUserData;
import org.itboys.admin.entity.BusinessCenterUser;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.admin.tools.LoginHolder;
import org.itboys.admin.tools.WebConstants;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.redis.RedisCacheClient;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

@Service
public class BusinessCenterUserService extends BaseAdminService<BusinessCenterUser, Long> {
	
	private static final long serialVersionUID = -6380030379631999515L;

    private static final String CENTER_ID_KEY = "USER_CENTER_ID-";

    private static final int CENTER_ID_EXPIRE = 24 * 3600;

	@Resource(name="adminDS")
	private MongoDataSource ds;

    @Autowired
    private RedisCacheClient redisCacheClient;
	
	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<BusinessCenterUser> getEntityClass() {
		return BusinessCenterUser.class;
	}

	public int updatePassword(long userId,String password){
		UpdateOperations<BusinessCenterUser> ops = ds.createUpdateOperations(BusinessCenterUser.class);
		ops.set("password", password);
		return update(userId, ops);
	}
	
	/**
	 * 组装登录人相关的信息
	 * @return
	 */
	public AdminUserData installAdminUserData(Long userId){
		AdminUserData aud = new AdminUserData();

        BusinessCenterUser adminUser = getById(userId);
		aud.setLogined(true);
		aud.setUsername(adminUser.getUsername());
		aud.setName(adminUser.getName());
		return aud;
	}

    public boolean existUser(long centerId) {
        return ds.createQuery(getEntityClass()).field("centerId").equal(centerId).asList().size() > 0;
    }

	/**
	 * 根据用户名查询用户
	 * 
	 * @param id
	 * @return
	 */
	public BusinessCenterUser getAdminUser(String userName) {
		// 用户名转小写再查
		List<BusinessCenterUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("username", userName).asList();
		return list==null||list.isEmpty()?null:list.get(0);
	}

    public long getUserCenterId(String userName) {
        /*Long value = redisCacheClient.get(CENTER_ID_KEY + userName, Long.class);
        if (value == null) {
            value = getAdminUser(userName).getCenterId();
            redisCacheClient.set(CENTER_ID_KEY + userName, value, CENTER_ID_EXPIRE);
        }
        return value;*/
        return 1;
    }

	/**
	 * 根据用户手机号查询用户
	 * 
	 * @param mobile
	 * @return
	 */
	public BusinessCenterUser getAdminUserByMoblie(String mobile) {
		List<BusinessCenterUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("mobile", mobile).asList();
		return list==null?null:list.get(0);
	}

	public boolean isExists(String userName) {
		List<BusinessCenterUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("username", userName).asList();
		return list.size() > 0;
	}
	
	/**
	 * 修改用户个人信息，不涉及到部门职务关联
	 * 
	 */
	public void doUpdateUserInfo(BusinessCenterUser user) {
		user.setPassword(getById(user.getId()).getPassword());
		user.setUsername(user.getUsername().toLowerCase());// 用户名转小写
		if (StringUtils.isEmpty(user.getBigLogo())) {
			user.setBigLogo(getById(user.getId()).getBigLogo());
		}
		AdminSessionHolder.prepareAdminLoginData(user);
		update(user);
	}

	/**
	 * 新增一个管理后台用户
	 * 
	 * @return
	 */
	public void insert(BusinessCenterUser user) {
		user.setPassword(Digests.md5(user.getPassword()));// 密码md5加密
		user.setUsername(user.getUsername().toLowerCase());// 用户名转小写
		AdminSessionHolder.prepareAdminLoginData(user);
		save(user);
	}

	/**
	 * 修改后台用户
	 * 
	 * @param id
	 * @return
	 */
	public void doUpdate(BusinessCenterUser user) {
		user.setPassword(getById(user.getId()).getPassword());
		user.setUsername(user.getUsername().toLowerCase());// 用户名转小写
		if(StringUtils.isEmpty(user.getBigLogo())){
			user.setBigLogo(getById(user.getId()).getBigLogo());
		}
		AdminSessionHolder.prepareAdminLoginData(user);
		update(user);
	}

	/**
	 * 修改密码
	 * 
	 * @param id
	 * @return
	 */
	public int updatePassword(String oldpass, String newpass, String upass) {
        BusinessCenterUser user = getById(LoginHolder.getLoginUser(WebConstants.SessionKey.ADMIN_USER).getUserid());
		if (user != null && StringUtils.equals(user.getPassword(), Digests.md5(oldpass))) {
			if (newpass.equals(upass)) {
				user.setPassword(Digests.md5(upass));
				AdminSessionHolder.prepareAdminLoginData(user);
				update(user);
				return 1;
			} else {
				return 2;
			}
		} else {
			return -1;
		}
	}

	/**
	 * 记下最后登入信息
	 * 
	 * @param id
	 * @return
	 */
	public void doLogin() {
        BusinessCenterUser au = new BusinessCenterUser();
		au.setId(AdminSessionHolder.getAdminUserId());
		au.setLoginIp(AdminSessionHolder.getLoginIp());
		au.setLoginTime(System.currentTimeMillis());
		update(au);
	}

	public int deleteBy(String userName,Long id) {
		List<BusinessCenterUser> list = ds.createQuery(getEntityClass()).filter("username", userName).filter("id", id).asList();
        BusinessCenterUser adminUser = new BusinessCenterUser();
		if(!list.isEmpty()){
			adminUser = list.get(0);
		}
		int result = update(adminUser.getId(), "isDeleted", 1);
		return result;
	}

	public void modifyPass(Long id, String newPassword) {
        BusinessCenterUser au = getById(id);
		au.setPassword(Digests.md5(newPassword));
		update(au);
	}
	
	/**
	 * 获取所有的用户列表(带分页)
	 * 
	 * @return
	 */
	public Page<BusinessCenterUser> findAllUserAndPage(HttpServletRequest request, long centerId){
        Map<String, Object> param = Maps.newHashMap();
        param.put("centerId", centerId);
		return pageQuery2(request, param);
	}


    /**
     * 修改商家账号的状态
     * @param sellerUserId
     * @param state 0：冻结  1：开通
     * @return
     */
    public boolean updateState(Long centerUserId, int state){
        try{
            update(centerUserId, "status", state);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("updateState error", e);
            return false;
        }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
